package com.sinosoft.msf.base.supplier.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sinosoft.msf.base.supplier.dao.base.*;
import com.sinosoft.msf.base.supplier.expection.BizException;
import com.sinosoft.msf.base.supplier.pojo.CompanyInfoPojo;
import com.sinosoft.msf.base.supplier.pojo.CompanyMarkInfoPojo;
import com.sinosoft.msf.base.supplier.pojo.Contract;
import com.sinosoft.msf.base.supplier.pojo.OptVo;
import com.sinosoft.msf.base.supplier.pojo.entity.*;
import com.sinosoft.msf.base.supplier.pojo.query.Sap001Vo;
import com.sinosoft.msf.base.supplier.props.FileTypeEnum;
import com.sinosoft.msf.base.supplier.props.UserRoleEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommonBizService {
    private static final  Logger log = LoggerFactory.getLogger(CommonBizService.class);
    @Autowired
    SCompanyInfoMapper sCompanyInfoMapper;
    @Autowired
    SCompanyFileMapper sCompanyFileMapper;
    @Autowired
    SCompanyContractMapper sCompanyContractMapper;
    @Autowired
    SCompanyInfoModifyingMapper sCompanyInfoModifyingMapper;
    @Autowired
    SAuditRecordMapper sAuditRecordMapper;
    @Autowired
    SProjectCompanyMapper sProjectCompanyMapper;
    @Autowired
    SSupDictMapper dictMapper;
    @Autowired
    CompanyUserRoleService roleService;
    @Autowired
    SCompanyScopeMapper scopeMapper;
    @Autowired
    SCompanyMapper sCompanyMapper;
    @Autowired
    SCompanyMarkMapper sCompanyMarkMapper;
    @Value("${common.getUserInfo.url:}")
    private String url;

//    public OptVo queryCureUserInfo() {
//        String token = "";
//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        if (requestAttributes != null) {
//            HttpServletRequest request = requestAttributes.getRequest();
//            token = request.getHeader("Authorization");
//        }else{
//            throw new BizException("请登录");
//        }
//        if (StrUtil.isEmpty(token)) {
//            throw new BizException("请登录");
//        }
//        log.info("token信息:{}", token);
//        String userJson = HttpRequest.post(url)
//                .header("Authorization", token).execute().body();
//        log.info("当前登录的用户信息为:{}", userJson);
//        if (StrUtil.isEmpty(userJson)) {
//            throw new BizException("用户信息不完整");
//        }
//        JSONObject dataObj = Optional.ofNullable(userJson).map(a -> JSON.parseObject(a)).map(a -> a.getJSONObject("data")).orElseThrow(() -> new BizException("用户信息不完整"));
//
//        OptVo vo = new OptVo();
//        vo.setUserId(dataObj.getString("userCode"));
//        vo.setUserName(dataObj.getString("name"));
//        vo.setDeptCode(dataObj.getString("sapDeptId"));
//        vo.setDeptName(dataObj.getString("sapDeptName"));
//
//        if(StrUtil.isEmpty(vo.getUserId()) && token.contains("uctoken")){
//            //集团token,再调用查询接口完善信息
//            String userId = dataObj.getString("id");
//            vo = queryUcUserInfo(userId,token);
//            if (vo == null) {
//                throw new BizException("用户信息不完整，无法操作该功能");
//            }
//        }
//
//        Set<String> roles = roleService.queryRole(vo);
//        vo.setAdminFlag(roles.contains(UserRoleEnum.admin.name()));
//        vo.setLegalFlag(roles.contains(UserRoleEnum.legal.name()) || roles.contains(UserRoleEnum.legal2.name()));
//        log.info("转换后的用户信息:{}", JSON.toJSONString(vo));
//        return vo;
//    }

    public OptVo queryCureUserInfo() {
        OptVo vo = new OptVo();
        vo.setUserId("DJ030502");
        vo.setUserName("熊大");
        Set<String> roles = roleService.queryRole(vo);
        vo.setAdminFlag(roles.contains(UserRoleEnum.admin.name()));
        vo.setLegalFlag(roles.contains(UserRoleEnum.legal.name()) || roles.contains(UserRoleEnum.legal2.name()));
        log.info("转换后的用户信息:{}", JSON.toJSONString(vo));
        return vo;
    }

    private OptVo queryUcUserInfo(String userId,String token) {
        Sap001Vo sap001Vo = new Sap001Vo();
        Sap001Vo.HeaderDTO headerDTO = new Sap001Vo.HeaderDTO();
        headerDTO.setSeriaNo("A002"+DateUtil.format(DateUtil.date(), "yyMMddHHmmssSSSS"));
        headerDTO.setTransCode("NQ001");
        headerDTO.setTransDate(DateUtil.today());
        headerDTO.setTransTime(DateUtil.formatTime(DateUtil.date()));
        headerDTO.setSysCode("A002");
        sap001Vo.setHeader(headerDTO);
        Sap001Vo.BodyDTO bodyDTO = new Sap001Vo.BodyDTO();
        bodyDTO.setQueryType("4");
        bodyDTO.setUserId(userId);
        sap001Vo.setBody(bodyDTO);
//        JSONObject res = "queryServiceFeign.SAP001(token,sap001Vo)";
        JSONObject res = new JSONObject();
        Optional<JSONArray> objects = Optional.ofNullable(res).map(a -> a.getJSONObject("data"))
                .map(a -> a.getJSONArray("PersonInfoList"));
        OptVo vo = new OptVo();
        if (objects.isPresent()) {
            JSONArray jsonArray = objects.get();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                vo.setUserId(jsonObject.getString("id"));
                vo.setUserName(jsonObject.getString("name"));
                vo.setDeptName(jsonObject.getString("company"));
                vo.setDeptCode(jsonObject.getString("companyId"));
                return vo;
            }
        }
        return null;
    }


    public String transCatWithList(List<CompanyInfoPojo.ScopeItem> supplierScope) {
        String catName = "";
        if(CollUtil.isNotEmpty(supplierScope)){
            catName = supplierScope.stream().map(it->{
                if (it.getCode().contains("99")) {
                    return it.getOther();
                }
                return it.getName();
            }).collect(Collectors.joining(","));
        }
        return catName;
    }
    public String transCat(String catId) {
        if (StrUtil.isEmpty(catId)) {
            return "";
        }
        List<SSupDict> sSupDicts = dictMapper.selectAll();
        String collect = Arrays.stream(catId.split(","))
                .map(id -> sSupDicts.stream().filter(sup -> sup.getCode().equals(id)).findFirst().orElse(new SSupDict()))
                .map(sup -> StrUtil.emptyToDefault(sup.getName(),"")).collect(Collectors.joining(","));
        return collect;
    }

    /**
     * 查询供应商详情
     *
     * @param id
     * @return
     */
    public CompanyInfoPojo queryCompanyDetail(String id) {
        return queryCompanyDetail(id, "");
    }
    public CompanyInfoPojo queryCompanyDetail(String id,String projectId) {
        return queryCompanyDetail(id, null, projectId, true);
    }
    public CompanyInfoPojo queryCompanyDetail(String id, String modifyId, String projectId,boolean cdnEncode) {
        CompanyInfoPojo companyInfoPojo = new CompanyInfoPojo();
        companyInfoPojo.setId(id);
        //查询供应商信息表
        SCompanyInfo sCompanyInfo = new SCompanyInfo();
        if (!StringUtils.isEmpty(modifyId)) {
            log.info("查询供应商修改信息表");
            SCompanyInfoModifying infoModifying = sCompanyMapper.selectCompanyModifyInfoById(modifyId);
            BeanUtils.copyProperties(infoModifying, sCompanyInfo);
            // 根据修改id查供应商相关信息
            id = modifyId;
        } else if (!StringUtils.isEmpty(id)) {
            log.info("查询供应商信息主表");
            sCompanyInfo = sCompanyInfoMapper.selectByPrimaryKey(id);
        }
        if (sCompanyInfo == null) {
//            throw new BizException("该供应商不存在，请核实供应商id");
            return companyInfoPojo;
        }

        BeanUtils.copyProperties(sCompanyInfo, companyInfoPojo);
        //查询联系人表
        List<Contract> contractList = queryContracts(id);
        companyInfoPojo.setContracts(contractList);
        companyInfoPojo.setLastSearchTime(DateUtil.formatDateTime(sCompanyInfo.getLastSearchTime()));
        companyInfoPojo.setLicenseStartDate(DateUtil.formatDate(sCompanyInfo.getLicenseStartDate()));
        companyInfoPojo.setLicenseEndDate(DateUtil.formatDate(sCompanyInfo.getLicenseEndDate()));
        companyInfoPojo.setCreatedDate(DateUtil.formatDateTime(sCompanyInfo.getCreatedDate()));
        companyInfoPojo.setUpdateDate(DateUtil.formatDateTime(sCompanyInfo.getUpdateDate()));
        companyInfoPojo.setPermitInDate(sCompanyInfo.getPermitInDate());
//        companyInfoPojo.setComId(sCompanyInfo.getShareholderChart());
        companyInfoPojo.setComId(sCompanyInfo.getTycComId());
        //查询公司经验范围表
        List<CompanyInfoPojo.ScopeItem> scopeItems = queryScopeById(id);
        companyInfoPojo.setSupplierScope(scopeItems);
        //查询文件表
        queryFile(id, companyInfoPojo,cdnEncode);
        //追加修改信息对象
        if ("y".equals(sCompanyInfo.getModified())) {
            SCompanyInfoModifying sCompanyInfoModifying = queryModCompany(sCompanyInfo.getModId());
            if (sCompanyInfoModifying != null) {
                CompanyInfoPojo companyInfoMod = new CompanyInfoPojo();
                BeanUtils.copyProperties(sCompanyInfoModifying, companyInfoMod);
                companyInfoMod.setLicenseStartDate(DateUtil.formatDate(sCompanyInfoModifying.getLicenseStartDate()));
                companyInfoMod.setLicenseEndDate(DateUtil.formatDate(sCompanyInfoModifying.getLicenseEndDate()));
                companyInfoMod.setLastSearchTime(DateUtil.formatDateTime(sCompanyInfoModifying.getLastSearchTime()));
                List<Contract> contractListMod = queryContracts(sCompanyInfoModifying.getId());
                companyInfoMod.setContracts(contractListMod);
                List<CompanyInfoPojo.ScopeItem> scopeModList = queryScopeById(sCompanyInfoModifying.getId());
                companyInfoMod.setSupplierScope(scopeModList);
                queryFile(sCompanyInfo.getModId(), companyInfoMod,cdnEncode);
                companyInfoPojo.setCompanyInfoMod(companyInfoMod);
            }
        }
        //查询审核记录
        if (StrUtil.isNotEmpty(sCompanyInfo.getLegalAuditId())) {
            SAuditRecord record = sAuditRecordMapper.selectByPrimaryKey(sCompanyInfo.getLegalAuditId());
            if (record != null) {
                CompanyInfoPojo.LegalAduit legalAduit = new CompanyInfoPojo.LegalAduit();
                legalAduit.setAuditResult(record.getAuditResult());
                legalAduit.setAuditRemark(record.getAuditRemark());
                companyInfoPojo.setAuditId(record.getAuditId());
                companyInfoPojo.setLegalAduit(legalAduit);
            }
        }
        if (StrUtil.isNotEmpty(sCompanyInfo.getAdminAuditId())) {
            SAuditRecord record = sAuditRecordMapper.selectByPrimaryKey(sCompanyInfo.getAdminAuditId());
            if (record != null) {
                CompanyInfoPojo.AdminAduit adminAduit = new CompanyInfoPojo.AdminAduit();
                adminAduit.setAuditResult(record.getAuditResult());
                adminAduit.setAuditRemark(record.getAuditRemark());
                companyInfoPojo.setAuditId(record.getAuditId());
                companyInfoPojo.setAdminAduit(adminAduit);
            }
        }
        //如果传了项目ID，合并项目的报价单
        if (StrUtil.isNotEmpty(projectId)) {
            String pricePath = queryPriceFile(projectId, id,cdnEncode);
            companyInfoPojo.setPricePath(pricePath);
        }
        //查询标记信息
        if (StrUtil.isNotEmpty(sCompanyInfo.getMarkId())) {
            CompanyMarkInfoPojo companyMarkInfoPojo = sCompanyMapper.selectCompanyMarkInfo(null, sCompanyInfo.getMarkId());
            companyMarkInfoPojo.setMarkFiles(sCompanyMapper.selectMarkFile(FileTypeEnum.MAPJF.name(), sCompanyInfo.getMarkId()));
            companyInfoPojo.setCompanyMark(companyMarkInfoPojo);
        }
        return companyInfoPojo;
    }

    private void queryFile(String id, CompanyInfoPojo companyInfoPojo,boolean cdnEncode) {
        SCompanyFile sCompanyFile = new SCompanyFile();
        sCompanyFile.setBizType("company");
        sCompanyFile.setBizId(id);
        sCompanyFile.setDeleted("n");
        List<SCompanyFile> sCompanyFileList = sCompanyFileMapper.select(sCompanyFile);
        List<String> rtfList = new ArrayList<>();
        List<String> nifList = new ArrayList<>();
        List<String> ajfList = new ArrayList<>();
        sCompanyFileList.forEach(companyFile -> {
//            if (cdnEncode) {
//                companyFile.setFilePath(CdnEncryUtil.toCdnUrl(companyFile.getFilePath()));
//            }else{
//                companyFile.setFilePath(CdnEncryUtil.toObsUrl(companyFile.getFilePath()));
//            }
            if (FileTypeEnum.RTF.name().equals(companyFile.getFileType())) {
                rtfList.add(companyFile.getFilePath());
            } else if (FileTypeEnum.NIF.name().equals(companyFile.getFileType())) {
                nifList.add(companyFile.getFilePath());
            } else if (FileTypeEnum.AJF.name().equals(companyFile.getFileType())) {
                ajfList.add(companyFile.getFilePath());
            } else if (FileTypeEnum.OTH.name().equals(companyFile.getFileType())) {
                List<CompanyInfoPojo.FileVo> otherFiles = companyInfoPojo.getOtherFiles();
                if (otherFiles == null) {
                    otherFiles = new ArrayList<>();
                    companyInfoPojo.setOtherFiles(otherFiles);
                }
                CompanyInfoPojo.FileVo fileVo = new CompanyInfoPojo.FileVo();
                fileVo.setFilePath(companyFile.getFilePath());
                fileVo.setFileName(companyFile.getFileName());
                otherFiles.add(fileVo);
            }
        });
        companyInfoPojo.setRelatedTransFile(rtfList);
        companyInfoPojo.setNoIllegalFile(nifList);
        companyInfoPojo.setAuthJoinFile(ajfList);
    }

    public CompanyInfoPojo queryHisDetail(String id) {
        CompanyInfoPojo companyInfoPojo = new CompanyInfoPojo();
        companyInfoPojo.setId(id);
        //查询供应商信息表
        SCompanyInfoModifying sCompanyInfo = queryModCompany(id);
        if (sCompanyInfo == null) {
//            throw new BizException("该供应商不存在，请核实供应商id");
            log.info("供应商信息记录不存在");
            return companyInfoPojo;
        }
        SCompanyInfo orgInfo = sCompanyInfoMapper.selectByPrimaryKey(sCompanyInfo.getBussId());
        if (sCompanyInfo == null) {
//            throw new BizException("该供应商不存在，请核实供应商id");
            log.info("供应商信息不存在");
            return companyInfoPojo;
        }

        BeanUtils.copyProperties(sCompanyInfo, companyInfoPojo);
        //查询联系人表
        List<Contract> contractList = queryContractsByModId(id);
        companyInfoPojo.setContracts(contractList);
        companyInfoPojo.setLastSearchTime(DateUtil.formatDateTime(sCompanyInfo.getLastSearchTime()));
        companyInfoPojo.setLicenseStartDate(DateUtil.formatDate(sCompanyInfo.getLicenseStartDate()));
        companyInfoPojo.setLicenseEndDate(DateUtil.formatDate(sCompanyInfo.getLicenseEndDate()));
        companyInfoPojo.setCreatedDate(DateUtil.formatDateTime(sCompanyInfo.getCreatedDate()));
        companyInfoPojo.setUpdateDate(DateUtil.formatDateTime(sCompanyInfo.getUpdateDate()));
        companyInfoPojo.setPermitInDate(orgInfo.getPermitInDate());
//        companyInfoPojo.setComId(sCompanyInfo.getShareholderChart());
        companyInfoPojo.setComId(orgInfo.getTycComId());
        //查询经营范围
        List<CompanyInfoPojo.ScopeItem> scopeItems = queryScopeByModId(id);
        companyInfoPojo.setSupplierScope(scopeItems);
        //查询文件表
        SCompanyFile sCompanyFile = new SCompanyFile();
        sCompanyFile.setBizType("company");
        sCompanyFile.setModId(id);
        List<SCompanyFile> sCompanyFileList = sCompanyFileMapper.select(sCompanyFile);
        List<String> rtfList = new ArrayList<>();
        List<String> nifList = new ArrayList<>();
        List<String> ajfList = new ArrayList<>();
        sCompanyFileList.forEach(companyFile -> {
//            companyFile.setFilePath(CdnEncryUtil.toCdnUrl(companyFile.getFilePath()));
            if (FileTypeEnum.RTF.name().equals(companyFile.getFileType())) {
                rtfList.add(companyFile.getFilePath());
            } else if (FileTypeEnum.NIF.name().equals(companyFile.getFileType())) {
                nifList.add(companyFile.getFilePath());
            } else if (FileTypeEnum.AJF.name().equals(companyFile.getFileType())) {
                ajfList.add(companyFile.getFilePath());
            } else if (FileTypeEnum.OTH.name().equals(companyFile.getFileType())) {
                List<CompanyInfoPojo.FileVo> otherFiles = companyInfoPojo.getOtherFiles();
                if (otherFiles == null) {
                    otherFiles = new ArrayList<>();
                    companyInfoPojo.setOtherFiles(otherFiles);
                }
                CompanyInfoPojo.FileVo fileVo = new CompanyInfoPojo.FileVo();
                fileVo.setFilePath(companyFile.getFilePath());
                fileVo.setFileName(companyFile.getFileName());
                otherFiles.add(fileVo);
            }
        });
        companyInfoPojo.setRelatedTransFile(rtfList);
        companyInfoPojo.setNoIllegalFile(nifList);
        companyInfoPojo.setAuthJoinFile(ajfList);
        return companyInfoPojo;
    }

    public List<CompanyInfoPojo.ScopeItem> queryScopeById(String id) {
        Example exp = new Example(SCompanyScope.class, true, true);
        exp.createCriteria().andEqualTo("bizId", id).andEqualTo("deleted", "n");
        return queryScopeById(exp);
    }
    public List<CompanyInfoPojo.ScopeItem> queryScopeByModId(String id) {
        Example exp = new Example(SCompanyScope.class, true, true);
        exp.createCriteria().andEqualTo("modId", id);
        return queryScopeById(exp);
    }
    private List<CompanyInfoPojo.ScopeItem> queryScopeById(Example exp) {

        List<SCompanyScope> sCompanyScopeList = scopeMapper.selectByExample(exp);
        if (CollUtil.isNotEmpty(sCompanyScopeList)) {
            return sCompanyScopeList.stream().map(sCompanyScope -> {
                CompanyInfoPojo.ScopeItem scopeItem = new CompanyInfoPojo.ScopeItem();
                scopeItem.setCode(Arrays.asList(sCompanyScope.getScopeCode().split(",")));
                scopeItem.setStrCode(sCompanyScope.getScopeCode());
                scopeItem.setName(sCompanyScope.getScopeName());
                scopeItem.setOther(sCompanyScope.getOtherName());
                return scopeItem;
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    public String queryPriceFile(String projectId, String supId,boolean cdnEncode) {
        SProjectCompany company = new SProjectCompany();
        company.setProjectId(projectId);
        company.setCompanyId(supId);
        company.setDeleted("n");
        List<SProjectCompany> companies = sProjectCompanyMapper.select(company);
        if (CollUtil.isEmpty(companies)) {
            return "";
        }
        if (companies.size()>1) {
            return "";
        }
        String priceFile = companies.get(0).getPriceFile();
//        if (cdnEncode) {
//            priceFile = CdnEncryUtil.toCdnUrl(priceFile);
//        }else{
//            priceFile = CdnEncryUtil.toObsUrl(priceFile);
//        }
        return priceFile;
    }
    /**
     * 查询修改后的供应商信息
     *
     * @param modifyId
     * @return
     */
    public SCompanyInfoModifying queryModCompany(String modifyId) {
        return sCompanyInfoModifyingMapper.selectByPrimaryKey(modifyId);
//        Example example = new Example(SCompanyInfoModifying.class);
//        example.createCriteria().andEqualTo("bussId", bussId).andEqualTo("deleted", "n").andCondition("order by created_date DESC LIMIT 1");
//        List<SCompanyInfoModifying> sCompanyInfoModifyingList = sCompanyInfoModifyingMapper.selectByExample(example);
//        if (CollUtil.isNotEmpty(sCompanyInfoModifyingList)) {
//            return sCompanyInfoModifyingList.get(0);
//        }
//        return null;
    }

    /**
     * 查询对应的联系人信息
     *
     * @param companyId
     * @return
     */
    public List<Contract> queryContracts(String companyId) {
        SCompanyContract sCompanyContract = new SCompanyContract();
        sCompanyContract.setCompanyId(companyId);
        sCompanyContract.setDeleted("n");
        return queryContracts(sCompanyContract);
    }
    public List<Contract> queryContractsByModId(String companyId) {
        SCompanyContract sCompanyContract = new SCompanyContract();
        sCompanyContract.setModId(companyId);
        return queryContracts(sCompanyContract);
    }
    public List<Contract> queryContracts(SCompanyContract sCompanyContract) {
        List<SCompanyContract> sCompanyContractList = sCompanyContractMapper.select(sCompanyContract);
        List<Contract> contractList = new ArrayList<>();
        if (CollUtil.isNotEmpty(sCompanyContractList)) {
            contractList = sCompanyContractList.stream()
                    .map(scc -> {
                        Contract contract = new Contract();
                        BeanUtils.copyProperties(scc, contract);
                        return contract;
                    })
                    .collect(Collectors.toList());
        }
        return contractList;
    }
}
